import React, { useEffect } from 'react';

const TrainOverlay = ({ trains, signals, lines, cellSize, gap, setLines, setTracklights }) => {
  const calculateCenter = (row, col) => ({
    x: col * (cellSize + gap) + cellSize / 2,
    y: row * (cellSize + gap) + cellSize / 2,
  });

  const getLineByNo = (no) => lines.find((l) => l.no === no);

    // 更新轨道占用状态
    useEffect(() => {
        setLines((prev) =>
          prev.map((line) => {
            const occupied = trains.some((train) =>
              train.trackNo.includes(line.no)
            );
            return { ...line, occupied };
          })
        );
      }, [trains, setLines]);

      useEffect(() => {
        if (!Array.isArray(signals)) return;
        setTracklights((prev) =>
          prev.map((light) => {
            const matched = signals.find((s) => s.name === light.name);
            return matched ? { ...light, state: matched.state } : light;
          })
        );
      }, [signals, setTracklights]);

  const renderTrain = (train) => {
    const { id, trackNo, offset, length } = train;
    const startX = (offset + 0.5) * (cellSize + gap);
    const endX = (offset + 0.5 + length) * (cellSize + gap);

    return trackNo.map((no, i) => {
      const line = getLineByNo(no);
      if (!line) return null;

      const p1 = calculateCenter(line.start.row, line.start.col);
      const p2 = calculateCenter(line.end.row, line.end.col);
      const dx = p2.x - p1.x;
      const dy = p2.y - p1.y;
      const dist = Math.sqrt(dx ** 2 + dy ** 2);
      if (dist === 0) return null;

      const ux = dx / dist;
      const uy = dy / dist;

      const lineMinX = Math.min(p1.x, p2.x);
      const lineMaxX = Math.max(p1.x, p2.x);
      const visibleStartX = Math.max(startX, lineMinX);
      const visibleEndX = Math.min(endX, lineMaxX);
      const segLength = (visibleEndX - visibleStartX)/ux;

      if (segLength <= 0) return null;

    //   const drawStart = p1.x < p2.x
    //     ? visibleStartX - lineMinX
    //     : lineMaxX - visibleEndX;
    
      const drawStart = (visibleStartX - lineMinX) / ux;

      const drawX = p1.x + ux * drawStart;
      const drawY = p1.y + uy * drawStart;
      const angle = Math.atan2(dy, dx) * (180 / Math.PI);

      return (
        <g key={`${id}-${no}`} transform={`translate(${drawX}, ${drawY}) rotate(${angle})`}>
          <rect
            x={0}
            y={-6}
            width={segLength}
            height={12}
            fill="darkgray"
            stroke="black"
          />
          {i === Math.floor(trackNo.length / 2) && (
            <text
              x={segLength / 2}
              y={-8}
              textAnchor="middle"
              fontSize={10}
              fill="#000"
            >
              {id}
            </text>
          )}
        </g>
      );
    });
  };

  return <g>{trains.flatMap(renderTrain)}</g>;
};

export default TrainOverlay;
